﻿using UnityEngine;


namespace HEFramework
{
    public static class HUDSystem
    {
        [EntitySystem]
        public class HUDAwakeSystem : AwakeSystem<HUD>
        {
            protected override void Awake(HUD _self)
            {
                var uc = _self.GetSceneChild<UIComponent>();
                if (uc == null)
                {
                    return;
                }


                _self.Open();
                _self.AddChild<HUDText>();
                _self.AddChild<HUDSlider>();
            }
        }


        [EntitySystem]
        public class HUDDestroySystem : DestroySystem<HUD>
        {
            protected override void Destroy(HUD _self)
            {
                _self.Close();
            }
        }


        public static void Open(this HUD _self)
        {
            var uc = _self.GetSceneChild<UIComponent>();
            if (uc == null)
            {
                return;
            }

            _self.UIWindowBehaviour = uc.PushUISyn(eUIFlag.HUD);
            _self.Bind();
        }

        public static void Bind(this HUD _self)
        {
        }

        public static void Close(this HUD _self)
        {
            if (_self.UIWindowBehaviour == null)
            {
                return;
            }

            _self.UIWindowBehaviour.Hide();
            _self.UIWindowBehaviour = null;
        }

        public static Vector2 SyncItemUIPos(this HUD _self, Vector3 _pos)
        {
            var camera = _self.GetSceneChild<GameCamera>();
            if (camera == null)
            {
                return Vector3.zero;
            }

            Vector3 screenPosition = camera.SceneCamera.WorldToScreenPoint(_pos);
            Vector2 uiPosition;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(
                (RectTransform)_self.UIWindowBehaviour.GetTransform(),
                screenPosition,
                camera.UICamera,
                out uiPosition);
            return uiPosition;
        }
    }
}